package com.zzyl.framework.interceptor;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    TokenService tokenService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 失败校验
        String token = request.getHeader("authorization");
        // 若token为空，返回false
        if (StrUtil.isBlank(token)) {
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
        Claims claims = tokenService.parseToken(token);
        // 解析token结果为空，反回false
        if (ObjectUtils.isNull(claims)) {
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
        Object userId = claims.get("userId");
        // 解析token结果获取的userId为空，返回false
        if (ObjectUtils.isNull(userId)) {
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
        // 二，校验成功之后获取用户信息存储到ThreadLocal
        UserThreadLocal.setValue(Long.valueOf(userId.toString()));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 调用结束后进行清除
        UserThreadLocal.clean();
    }
}
